package com.sxwl.exception;
import com.sxwl.vo.JsonData;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
 * @author reading
 * @Description TODO
 * @Date 2020/3/8 13:16
 */
@RestControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(RuntimeException.class)
    public JsonData handlerException(MyException e){
        return  JsonData.fail(e.getMessage());
    }
    @ExceptionHandler(value = BindException.class)
    public JsonData validatorException(BindException e) {
        BindingResult result = e.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        for (ObjectError error : result.getAllErrors()) {
            errorMsg.append(error.getDefaultMessage()).append(",");
        }
        errorMsg.delete(errorMsg.length() - 1, errorMsg.length());
        return JsonData.fail(errorMsg.toString());
    }
}
